import 'dart:async';
import 'dart:convert' as convert;
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:bubble/bubble.dart';

// import 'package:camera/camera.dart';
import 'package:chathouse/pages/expert/buyWallet/recharge_bank_card.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/log.dart';
import 'package:chathouse/web_socket/web_socket_channel.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
import 'package:flutter_chat_ui/flutter_chat_ui.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:uuid/uuid.dart';

import '../constant/app_constant.dart';
import '../model/chat_detail_info.dart';
import '../model/chat_record.dart';
import '../model/member_info.dart';
import '../model/response_bean.dart';
import '../pages/client/order/comment_order_page.dart';
import '../public/event_bus.dart';
import '../util/DateUtil.dart';
import '../util/base_utils.dart';
import '../widgets/form_widgets/widget_paras.dart';
import '../widgets/my_input_widget.dart';
import 'chat_type.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

/// @class : chat_page
/// @date : 2023-03-10 16:10
/// @name : LFC
/// @description :
/// 坑：Expanded仅应在Row，Column或者Flex使用 否則 打包release 會報錯 ， 儘管deBug沒問題
///TODO 天頁面  後續把相機，畫廊代碼抽出去

class ChatPage extends StatefulWidget {
  Map message;

  ChatPage(this.message, {Key? key}) : super(key: key);

  @override
  State<ChatPage> createState() => _ChatPageState(message);
}

class _ChatPageState extends State<ChatPage> {
  final List<types.Message> _messages = [];
  final Map message;

  //構建當前用戶角色
  types.User? _user;

  TextEditingController inputController = TextEditingController();
  MemberInfo? memberInfo;
  StreamSubscription? refreshSubscription;

  _ChatPageState(this.message);

  var isNeedUpdate = false; //是否需要更新上一個界面

  TextEditingController inputLabelController = TextEditingController();

  ChatDetailInfo? chatDetailInfo;

  List<String>? labelList = ["+ 加標籤"];

  bool showImageGallery = false; //是否显示画廊
  int initPageIndex = 0;
  PageController? _pageController;

  // late CameraController cameraController;
  bool showCamera = false;
  XFile? _imageFile;
  bool cameraAccessDenied = false;

  int pageNum = 1;

  final AutoScrollController _chatScrollController = AutoScrollController();


  @override
  void initState() {
    super.initState();
    // cameraController = CameraController(cameras[0], ResolutionPreset.max);
    // cameraController.initialize().then((_) {
    //   if (!mounted) {
    //     return;
    //   }
    //   // cameraController?.stopImageStream()
    //   setState(() {});
    // }).catchError((Object e) {
    //   if (e is CameraException) {
    //     switch (e.code) {
    //       case 'CameraAccessDenied':
    //         setState(() {
    //           showCamera = false;
    //           cameraAccessDenied = false;
    //         });
    //         // Handle access errors here.
    //         break;
    //       default:
    //       // Handle other errors here.
    //         break;
    //     }
    //   }
    // });
    eventBus.fire(UpdateMsgReadEvent());
    Object? json = SpUtil.getObject2(AppConstant.memberInfo);
    if (json != null) {
      memberInfo = MemberInfo.fromJson2(json);
      LogUtil.d("當前用戶的編號： ${memberInfo?.data?.membersNo.toString() ?? ""}");
      _user = types.User(
          id: memberInfo?.data?.membersNo.toString() ?? "",
          role: types.Role.user);

      /// 查询聊天记录
      dynamic reviceuserId = message['reviceuserId'];
      dynamic projectNo = message['projectNo'];

      final params = {
        "reviceuserid": reviceuserId,
        "projectNo": projectNo,
        "pageNum": pageNum
      };
      Obj.showLoading();
      Apis.getMessageChatRecord(params).then((value) {
        Obj.dismissLoading();
        var json = value?.data;
        var chatRecord = ChatRecord.fromJson(json);
        LogUtil.d("chatRecord ${chatRecord.rows?.length}");
        _loadMessages(chatRecord);
        setState(() {});
      }).onError((error, stackTrace) {
        Obj.dismissLoading();
      });

      ///修改為已讀聊天狀態
      updateChatReadState();
    }

    ///獲取標籤等詳細信息
    getDetailOfLabel();

    ///收到信息監聽
    refreshSubscription = eventBus.on<OnMsgUpdate>().listen((event) {
      LogUtil.d("聊天页面收到廣播收到廣播收到廣播");
      Map<String, dynamic>? map = event.map;
      String msgtype = map!["msgtype"] ?? "";
      String senduserid = map["senduserid"] ?? "";
      String reciveuserid = map["reciveuserid"] ?? "";
      String sendtime = map["sendtime"] ?? "";
      String sendtext = map["sendtext"] ?? "";
      if (senduserid == reciveuserid ||
          senduserid == memberInfo?.data?.membersNo) {
        //發送方和接收方都是同一個人的時候 不用處理
        return;
      }

      ///如果收到了其他人发来的信息 不用实时插进列表
      if (message['reviceuserId'] != senduserid) {
        return;
      }
      addNewMsgToList(
          msgtype: msgtype,
          senduserid: senduserid,
          id: const Uuid().v4(),
          sendtime: sendtime,
          sendtext: sendtext,
          isFromEventBus: true);
      //增加个 mounted 属性是否存在的判断即可。
      if (mounted) {
        setState(() {});
      }

      ///修改為已讀聊天狀態
      updateChatReadState();
    });

    _chatScrollController.addListener(() {
      if (_chatScrollController.position.pixels ==
          _chatScrollController.position.maxScrollExtent) {
        // 到达最底部，执行你需要的操作
        // ToastUtil.showToast("到达最底部，执行你需要的操作");
      }
    });

  }



  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (showImageGallery) {
          setState(() {
            showImageGallery = false;
          });
          return false;
        }
        // if (showCamera) {
        //   setState(() {
        //     showCamera = false;
        //     // cameraController.setFlashMode(FlashMode.off);
        //   });
        //   return false;
        // }
        //刷新列表 和未读数量
        LogUtil.d("刷新列表 和未读数量");
        eventBus.fire(UpdateMsgReadEvent());
        eventBus.fire(UpdateClientMsgListEvent());
        // 返回true表示允许页面返回，false表示禁止页面返回
        return true;
      },
      child: Stack(
        children: [
          Scaffold(
            // resizeToAvoidBottomInset: false,
            appBar: PreferredSize(
              child: Container(
                color: Colors.white,
                child: Row(
                  children: [
                    ImageUtils.image(Res.icon_back, width: 26.w, height: 26.w)
                        .setContainer(
                      margin: EdgeInsets.only(
                          left: 22.w, top: Platform.isIOS ? 24.w : 12.w),
                    )
                        .setOnClickListener(() {
                      eventBus.fire(UpdateMsgReadEvent());
                      FocusManager.instance.primaryFocus?.unfocus();
                      Get.back(result: isNeedUpdate);
                      // Get.offAll(const ClientRootPage());
                      eventBus.fire(ToMsgTabEvent());
                    }, isInkWell: true),
                    Flexible(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          ImageUtils.image(widget.message["memberImage"] ?? "",
                                  width: 42.w,
                                  height: 42.w,
                                  radius: 21.w,
                                  imageType: ImageType.NETWORK)
                              .setContainer(
                            margin: EdgeInsets.only(
                                right: 6.w, top: Platform.isIOS ? 24.w : 12.w),
                          ),
                          Text(
                            widget.message["membersName"] ?? "",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: getTextStyle(22.sp,
                                color: Colors.black, fontType: FontType.BOLD),
                          ).setContainer(
                            margin: EdgeInsets.only(
                                right: 6.w, top: Platform.isIOS ? 24.w : 12.w),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: 26.w + 22.w + 6.w,
                    )
                  ],
                ),
              ),
              preferredSize:
                  Size(ScreenUtil().screenWidth, Platform.isIOS ? 60.w : 64.w),
            ),
            body: SafeArea(
              child: Stack(
                children: [
                  Chat(
                    messages: _messages,
                    onAttachmentPressed: _handleAttachmentPressed,
                    onMessageTap: _handleMessageTap,
                    disableImageGallery: true,
                    onPreviewDataFetched: _handlePreviewDataFetched,
                    scrollController: _chatScrollController,
                    onSendPressed: _handleSendPressed,
                    user: _user!,
                    bubbleBuilder: _bubbleBuilder,
                    textMessageBuilder: _textMessageBuilder,
                    imageMessageBuilder: customImageMessageBuilder,

                    ///去掉默認頭時間UI
                    dateHeaderBuilder: (dateHeader) {
                      return Container();
                    },

                    ///自定義發送狀態佈局
                    // customStatusBuilder: (types.Message message,
                    //     {required BuildContext context}) {
                    //   return Container(
                    //     // width: 10,
                    //     // height: 10,
                    //     color: Colors.black,
                    //   );
                    // },

                    ///自定義底部的佈局
                    customBottomWidget: getCustomBottomWidget(),
                    theme: DefaultChatTheme(
                      sentMessageBodyTextStyle: getTextStyle(18.sp,
                          color: Colors.black, fontType: FontType.MID),
                      sentMessageCaptionTextStyle: getTextStyle(18.sp,
                          color: Colors.black, fontType: FontType.MID),
                      receivedMessageBodyTextStyle: getTextStyle(18.sp,
                          color: Colors.black, fontType: FontType.MID),
                      receivedMessageCaptionTextStyle: getTextStyle(18.sp,
                          color: Colors.black, fontType: FontType.MID),
                    ),

                    // fileMessageBuilder: _buildCustomMessage,
                    // customMessageBuilder: _buildCustomMessage,
                  ),

                  ///加標籤
                  Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      child: Visibility(
                        visible: AppConstant.userRole == UserRole.b,
                        child: Column(
                          children: [
                            Padding(
                              padding: EdgeInsets.all(16.w),
                              child: Align(
                                  alignment: Alignment.topRight,
                                  child: Icon(
                                    Icons.edit_calendar,
                                    size: 30.w,
                                  )),
                            ).setOnClickListener(() {
                              setState(() {
                                editLabelStatus = !editLabelStatus;
                              });
                            }),
                            Expanded(
                              child: ListView.separated(
                                  scrollDirection: Axis.horizontal,
                                  itemBuilder:
                                      (BuildContext context, int index) {
                                    return getLabelWidget(index);
                                  },
                                  separatorBuilder:
                                      (BuildContext context, int index) {
                                    return SizedBox(
                                      width: 10.w,
                                    );
                                  },
                                  itemCount: labelList!.length),
                            )
                          ],
                        ).setContainer(
                            margin: EdgeInsets.only(left: 8.w, right: 8.w),
                            color: MyColors.gary_232233237,
                            height: 104.w),
                      ))
                ],
              ),
            ),
          ),

          ///图片浏览器（画廊）
          Visibility(
            visible: showImageGallery,
            child: Container(
              width: 1.sw,
              height: 1.sh,
              color: Colors.black,
              child: Stack(
                children: [
                  Positioned(
                    top: 0,
                    bottom: 0,
                    left: 0,
                    right: 0,
                    child: PageView.builder(
                      reverse: true,
                      controller: _pageController,
                      itemCount: imgList.length,
                      itemBuilder: (BuildContext context, int index) {
                        if (!imgList[index].startsWith("http")) {
                          return ExtendedImage.file(File(imgList[index]));
                        } else {
                          return ExtendedImage.network(
                            imgList[index],
                            fit: BoxFit.fitWidth,
                            cache: true,
                            mode: ExtendedImageMode.gesture,
                            onDoubleTap: (ExtendedImageGestureState state) {
                              ///you can use define pointerDownPosition as you can,
                              ///default value is double tap pointer down position.
                              // ToastUtil.showToast("msg");
                            },
                            initGestureConfigHandler: (state) {
                              return GestureConfig(
                                minScale: 0.9,
                                animationMinScale: 0.7,
                                maxScale: 3.0,
                                animationMaxScale: 3.5,
                                speed: 1.0,
                                inertialSpeed: 100.0,
                                initialScale: 1.0,
                                inPageView: true,
                                initialAlignment: InitialAlignment.center,
                              );
                            },
                            //cancelToken: cancellationToken,
                          );
                        }

                        // return Image.network(imgList[index], fit: BoxFit.fitWidth)
                        //     .setOnClickListener(() {
                        //   setState(() {
                        //     showImageGallery = false;
                        //   });
                        // });
                      },
                    ).setOnClickListener(() {
                      setState(() {
                        showImageGallery = false;
                      });
                    }),
                  ),
                  Positioned(
                    top: 30.w,
                    right: 20,
                    child: Icon(
                      Icons.close,
                      color: Colors.white,
                      size: 50.w,
                    ).setOnClickListener(() {
                      setState(() {
                        showImageGallery = false;
                      });
                    }),
                  )
                ],
              ),
            ),
          ),

          ///相機
          // Visibility(
          //   visible: showCamera,
          //   child: Container(
          //     width: 1.sw,
          //     height: 1.sh,
          //     child: Stack(
          //       children: [
          //         Container(
          //           width: 1.sw,
          //           height: 1.sh,
          //           child: CameraPreview(cameraController),
          //         ),
          //         Align(
          //           alignment: Alignment.bottomCenter,
          //           child: Padding(
          //             padding: const EdgeInsets.all(32.0),
          //             child: ElevatedButton(
          //               onPressed: () async {
          //                 final XFile file =
          //                 await cameraController.takePicture();
          //                 LogUtil.d("file ${file.path}");
          //                 // 处理拍摄的照片
          //                 setState(() {
          //                   _imageFile = file;
          //                   // Turn off the flash
          //                   cameraController.setFlashMode(FlashMode.off);
          //                 });
          //
          //                 final result = await Get.to(PreviewScreen(file));
          //                 if (result == 100) {
          //                   setState(() {
          //                     showCamera = false;
          //                     // Toggle the flash state
          //                   });
          //                   //發送圖片操作
          //                   if (_imageFile == null) {
          //                     return;
          //                   }
          //                   uploadImageOfCamera(_imageFile!);
          //                 }
          //               },
          //               child: const Text('點擊拍照'),
          //             ),
          //           ),
          //         ),
          //         Align(
          //           alignment: Alignment.topLeft,
          //           child: Padding(
          //             padding: EdgeInsets.only(top: 60.w, left: 20.w),
          //             child: IconButton(
          //               icon: const Icon(
          //                 Icons.arrow_back_ios_new_sharp,
          //                 color: Colors.white,
          //               ),
          //               onPressed: () {
          //                 setState(() {
          //                   showCamera = false;
          //                   cameraController.setFlashMode(FlashMode.off);
          //                 });
          //               },
          //             ),
          //           ),
          //         ),
          //       ],
          //     ),
          //   ),
          // )
        ],
      ),
    );
  }

  List<String> imgList = [];

  bool editLabelStatus = false; //是否是編輯標籤狀態

  ///標籤部分显示
  Widget getLabelWidget(index) {
    if (labelList![index].isEmpty) {
      return Container();
    }
    return Stack(
      children: [
        Text(
          labelList![index],
          style:
              getTextStyle(16.sp, color: Colors.black, fontType: FontType.BOLD),
        ).setContainer(
            padding: EdgeInsets.only(left: 15.w, right: 15.w),
            alignment: Alignment.center,
            margin: EdgeInsets.only(left: 10.w, bottom: 10.w),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(14.w))),
        Positioned(
          top: 0,
          right: 0,
          child: Visibility(
              visible: editLabelStatus && index != 0,
              child: Icon(
                Icons.delete_forever,
                color: Colors.red,
                size: 20.w,
              )).setOnClickListener(() {
            Get.defaultDialog(
                title: "確定刪除嗎？",
                textCancel: "取消",
                textConfirm: "確定",
                middleText: "",
                buttonColor: Colors.white,
                cancelTextColor: MyColors.black_0000011,
                confirmTextColor: MyColors.black_0000011,
                radius: 20.w,
                titlePadding: EdgeInsets.all(20.w),
                onConfirm: () {
                  labelList!.removeAt(index);
                  updateLabels();
                  setState(() {});
                },
                onCancel: () {
                  // Get.back();
                });
          }),
        )
      ],
    ).setOnClickListener(() {
      if (index != 0) {
        return;
      }
      FocusManager.instance.primaryFocus?.unfocus();
      Get.bottomSheet(
          ListView(
            children: [
              MyInputWidget(
                title: "請輸入標籤內容",
                textStyle: getTextStyle(18.sp, fontType: FontType.MID),
                controller: inputLabelController,
              ).setContainer(margin: EdgeInsets.only(top: 12.w)),
              SizedBox(
                height: 40.w,
              ),
              Row(
                //必须加Row 不加 会铺满宽度  无法指定宽度
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("保存", style: getTextStyle(20.sp, color: Colors.white))
                      .setContainer(
                    height: 50.w,
                    width: 150.w,
                    decoration: BoxDecoration(
                        color: MyColors.green_6915761,
                        borderRadius: BorderRadius.circular(25.w)),
                    alignment: Alignment.center,
                  )
                      .setOnClickListener(() {
                    //TODO 保存
                    if (inputLabelController.text.toString().isEmpty) {
                      ToastUtil.showToast("輸入內容不能為空！");
                      return;
                    }
                    updateLabels();
                  }, isInkWell: true),
                ],
              )
            ],
          ).setContainer(
            decoration: BoxDecoration(
                color: const Color.fromRGBO(255, 255, 255, 1),
                borderRadius: BorderRadius.circular(22.w)),
            padding: EdgeInsets.only(top: 30.w, left: 30.w, right: 30.w),
          ),
          backgroundColor: Colors.white);
    });
  }

  ///更新标签接口
  void updateLabels() {
    Obj.showLoading();
    var projectId = widget.message["projectId"];
    final pa = {"projectId": projectId};
    Apis.queryChatDetailOfProjectId(pa).then((value) {
      Obj.dismissLoading();
      var result = ChatDetailInfo.fromJson(value?.data ?? {});
      if (result.code == 200) {
        var projectNo = widget.message["projectNo"];
        labelList!.add(inputLabelController.text.toString());
        List<String> tmpList = [];
        tmpList.addAll(labelList!);
        tmpList.removeAt(0);
        var labelText = tmpList.join(",");
        final params = {
          "id": result.data?.id,
          "projectLabel": labelText,
          "projectId": projectId,
          "projectNo": projectNo,
          "version": result.data?.version
        };
        Obj.showLoading();
        Apis.updateChatRecord(params).then((value) {
          Obj.dismissLoading();
          var result = ResponseBean.fromJson(value?.data ?? {});
          if (result.isRequestSuccess) {
            ToastUtil.showToast("保存成功");
            inputLabelController.clear();
            //TODO 往listView 後面加一個元素
            // labelList!.add(inputLabelController.text);
            // LogUtil.d("last labelList:$labelList");
            // setState(() {});
            getDetailOfLabel();
            Get.back();
          }
        }).catchError((error) {
          LogUtil.d("updateChatRecord error $error");
          Obj.dismissLoading();
        });
      }
    }).catchError((error) {
      LogUtil.d("updateChatRecord error $error");
      Obj.dismissLoading();
    });
  }

  ///自定义图片消息
  Widget customImageMessageBuilder(types.ImageMessage imageMessage,
      {required int messageWidth}) {
    String formatTime = getFormatSendTime(imageMessage);
    // LogUtil.d("imageMessage.uri } ${imageMessage.uri}");
    return Container(
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(6.w)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ImageUtils.image(
            imageMessage.uri,
            imageType: (imageMessage.uri.startsWith("http"))
                ? ImageType.NETWORK
                : ImageType.FILE,
            width: ScreenUtil().screenWidth / 2,
          ),
          SizedBox(
            height: 6.w,
          ),
          Text(formatTime,
              style: getTextStyle(20.sp,
                  color: MyColors.gary_000003, fontType: FontType.BOLD)),
        ],
      ),
    );
  }

  ///自定義文字消息UI
  Widget _textMessageBuilder(
    types.TextMessage textMessage, {
    required int messageWidth,
    required bool showName,
  }) {
    ///是否本人呢
    var isSelf = _user!.id == textMessage.author.id;
    String formatTime = getFormatSendTime(textMessage);

    return Column(
      crossAxisAlignment:
          isSelf ? CrossAxisAlignment.end : CrossAxisAlignment.start,
      children: [
        Text(
          textMessage.text,
          style: getTextStyle(20.sp,
              color: MyColors.black_0000011, fontType: FontType.BOLD),
        ),
        SizedBox(
          height: 6.w,
        ),
        Text(formatTime,
            style: getTextStyle(20.sp,
                color: MyColors.gary_000003, fontType: FontType.BOLD)),
      ],
    );
  }

  ///自定義底部UI
  Widget getCustomBottomWidget() {
    return Column(
      children: [
        Visibility(
          visible: AppConstant.userRole == UserRole.c,
          child: Container(
            margin: EdgeInsets.only(bottom: 6.w),
            height: 65.w,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(
                      10.w,
                    ),
                    topRight: Radius.circular(10.w)),
                border: Border.all(width: 1.w, color: MyColors.gary_210210210)),
            child: Padding(
              padding: EdgeInsets.only(left: 16.w, right: 8.w),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(widget.message["membersName"] ?? "",
                      style: getTextStyle(20.sp,
                          color: Colors.black, fontType: FontType.BOLD)),
                  const Spacer(),
                  Visibility(
                    visible: message['exhibition'] ?? false,
                    child: Text(
                      "聘用",
                      style: getTextStyle(20.sp,
                          color: Colors.white, fontType: FontType.BOLD),
                    )
                        .setContainer(
                            padding: EdgeInsets.symmetric(
                                horizontal: 18.w, vertical: 2.w),
                            decoration: BoxDecoration(
                                color: MyColors.green_69157608,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(15.w))))
                        .setOnClickListener(() {
                      hire();
                    }),
                  ),
                  SizedBox(
                    width: 8.w,
                  ),
                  Visibility(
                    visible: message['evaluate'] ?? false,
                    child: Text(
                      "評語",
                      style: getTextStyle(20.sp,
                          color: Colors.white, fontType: FontType.BOLD),
                    )
                        .setContainer(
                            padding: EdgeInsets.symmetric(
                                horizontal: 18.w, vertical: 2.w),
                            decoration: BoxDecoration(
                                color: MyColors.green_69157608,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(15.w))))
                        .setOnClickListener(() {
                      FocusManager.instance.primaryFocus?.unfocus();
                      Get.to(
                          CommentOrderPage(widget.message["projectNo"] ?? ""));
                    }),
                  ),
                ],
              ),
            ),
          ),
        ),
        Padding(
          padding:
              EdgeInsets.only(left: 16.w, right: 8.w, top: 4.w, bottom: 4.w),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              ImageUtils.image(Res.icon_upload_attachment,
                      fit: BoxFit.fitWidth, width: 30.w)
                  .setOnClickListener(() {
                _handleAttachmentPressed();
              }),
              SizedBox(
                width: 14.w,
              ),
              Flexible(
                child: Container(
                  height: INPUT_ITEM_HEIGHT.w,
                  padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 0),
                  decoration: BoxDecoration(
                      border: Border.all(
                          color: MyColors.gary_226226226, width: 1.w),
                      borderRadius: BorderRadius.circular(45.w)),
                  child: Row(
                    children: [
                      Flexible(
                          child: TextField(
                        onChanged: (text) {
                          // inputController.text = text;
                          inputController.selection =
                              TextSelection.fromPosition(TextPosition(
                                  affinity: TextAffinity.downstream,
                                  offset: inputController.text.length));
                          setState(() {});
                        },
                        textAlign: TextAlign.start,
                        controller: inputController,
                        style: getTextStyle(18.sp,
                            color: Colors.black, fontType: FontType.MID),
                        decoration: InputDecoration(
                          /// 让文字垂直居中
                          focusedBorder: const OutlineInputBorder(
                              borderSide: BorderSide(
                                  width: 0, color: Colors.transparent)),

                          disabledBorder: const OutlineInputBorder(
                              borderSide: BorderSide(
                                  width: 0, color: Colors.transparent)),

                          enabledBorder: const OutlineInputBorder(
                              borderSide: BorderSide(
                                  width: 0, color: Colors.transparent)),

                          border: const OutlineInputBorder(
                              borderSide: BorderSide(
                                  width: 0, color: Colors.transparent)),

                          contentPadding: EdgeInsets.only(top: 0, bottom: 6.w),
                          hintText: "輸入你的訊息",
                          hintStyle: getTextStyle(18.sp,
                              color: MyColors.gary_155155155,
                              fontType: FontType.MID),
                          // border: InputBorder.none,
                        ),
                        keyboardType: TextInputType.multiline,
                        maxLines: null,
                      )),
                    ],
                  ),
                ),
              ),
              SizedBox(
                width: 14.w,
              ),
              ImageUtils.image(
                      inputController.text.isNullOrEmpty
                          ? Res.icon_send_msg_gray
                          : Res.icon_send_msg_green,
                      width: 30.w,
                      height: 26.w)
                  .setOnClickListener(() {
                String text = inputController.text.trim();
                if (text.isNullOrEmpty) {
                  ToastUtil.showToast("輸入內容不能為空");
                  return;
                }
                _handleSendPressed(types.PartialText(text: text));
                //清空輸入框
                inputController.clear();
                // FocusManager.instance.primaryFocus?.unfocus();
              }),
            ],
          ),
        )
      ],
    );
  }

  ///獲取發送時間---格式化後
  String getFormatSendTime(types.Message textMessage) {
    final dateTime = DateTime.fromMillisecondsSinceEpoch(textMessage.createdAt!,
        isUtc: false);
    var formatTime = "";
    try {
      if (DateUtil.isToday(dateTime)) {
        formatTime = DateFormat("k:mm:ss a").format(dateTime);
      } else if (DateUtil.isYesterday(dateTime)) {
        formatTime = DateFormat("昨天 k:mm:ss a").format(dateTime);
      } else {
        formatTime = DateUtil.getFormattedTime_(textMessage.createdAt!);
      }
    } catch (e) {
      formatTime = DateUtil.getNowTimeStr();
    }
    return formatTime;
  }

  ///自定義氣泡UI
  Widget _bubbleBuilder(
    Widget child, {
    required message,
    required nextMessageInGroup,
  }) =>
      Bubble(
        elevation: 0,
        color: _user!.id != message.author.id ||
                message.type == types.MessageType.image
            ? const Color(0xfff5f5f7)
            : AppConstant.userRole == UserRole.c
                ? const Color(0x6163A968)
                : MyColors.green_6915715408,
        margin: const BubbleEdges.symmetric(horizontal: 6),
        showNip: false,
        radius: Radius.circular(6.w),
        padding: message.type == types.MessageType.image
            ? const BubbleEdges.all(0)
            : const BubbleEdges.all(16),
        child: child,
      );

  ///插入一條消息到當前聊天列表
  addNewMsgToList(
      {msgtype, senduserid, id, sendtime, sendtext, isFromEventBus = false}) {
    types.Message msg;
    var user = types.User(id: senduserid.toString(), role: types.Role.user);
    if (msgtype == MsgType.TEXT_TYPE) {
      msg = types.TextMessage(
          remoteId: senduserid,
          type: types.MessageType.text,
          author: user,
          id: const Uuid().v4(),
          createdAt: DateUtil.dateToTimestamp(sendtime.toString(),
              isMicroseconds: false),
          text: sendtext.toString());
      if (isFromEventBus) {
        _messages.insert(0, msg);
      } else {
        _messages.add(msg);
      }
    } else if (msgtype == MsgType.IMAGE_TYPE) {
      // final _user =
      //     types.User(id: senduserid.toString(), role: types.Role.user);
      try {
        msg = types.ImageMessage(
          remoteId: senduserid,
          type: types.MessageType.image,
          uri: sendtext ?? "",
          size: 0,
          name: "imageName",
          author: user,
          id: const Uuid().v4(),
          createdAt: DateUtil.dateToTimestamp(sendtime.toString(),
              isMicroseconds: false),
        );

        if (isFromEventBus) {
          _messages.insert(0, msg);
        } else {
          _messages.add(msg);
        }
      } catch (e) {
        LogUtil.d("bytes error ${e.toString()}");
      }
    }
  }

  ///通過WebSocket 發送消息到服務端並且更新ChatList
  void _addMessage(types.Message message, {String? imgUrl = ""}) {
    String type = MsgType.TEXT_TYPE;
    types.TextMessage? textMessage;
    if (message is types.TextMessage) {
      textMessage = message;
    } else if (message is types.ImageMessage) {
      type = MsgType.IMAGE_TYPE;
      LogUtil.d("IMAGE_TYPE _messages  ${message.uri}");
    } else if (message is types.FileMessage) {
      types.FileMessage fileMessage = message;
    }
    //圖片、文字 都是sendtext
    final map = {
      "senduserid": memberInfo?.data?.membersNo,
      "reciveuserid": widget.message['reviceuserId'],
      "projectNo": widget.message["projectNo"],
      "msgtype": type,
      'sendtext': type == MsgType.TEXT_TYPE ? textMessage?.text : imgUrl,
      'sendtime': DateUtil.getNowTimeStr_(),
      'id': memberInfo?.data?.membersId,
    };
    MyWebSocketChannel.instance.sendMessage(convert.jsonEncode(map));
    setState(() {
      _messages.insert(0, message);
    });
  }

  void _handleAttachmentPressed() {
    debugPrint("_handleAttachmentPressed");
    showModalBottomSheet<void>(
      context: context,
      builder: (BuildContext context) => SafeArea(
        child: Container(
          alignment: Alignment.center,
          height: 140.w,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                  _handleImageSelection(ImageSource.gallery);
                },
                child: Align(
                  alignment: AlignmentDirectional.center,
                  child: Text(
                    '從相冊中選取',
                    style: getTextStyle(20.sp, color: Colors.black),
                  ),
                ),
              ),
              Container(
                width: double.infinity,
                height: 0.5.w,
                color: Colors.grey,
              ),
              TextButton(
                onPressed: () {
                  // if (!cameraAccessDenied) {
                  //   ToastUtil.showToast("CameraAccessDenied");
                  //   return;
                  // }
                  // // Navigator.pop(context);
                  // Get.back();
                  // setState(() {
                  //   showCamera = true;
                  // });

                  Navigator.pop(context);
                  _handleImageSelection(ImageSource.camera);
                },
                child: Align(
                  alignment: AlignmentDirectional.center,
                  child: Text(
                    '相機',
                    style: getTextStyle(20.sp, color: Colors.black),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  ///上傳圖片
  void uploadImageOfCamera(XFile image) async {
    var imgData = await image.readAsBytes();
    if (imgData == null) return;

    Obj.showLoading();
    imgData = await testComporessList(imgData);

    final uiImage = await decodeImageFromList(imgData);

    ///1.先上傳圖片到服務器
    ///2.失敗的話狀態改失敗 再add進去
    Obj.showLoading();
    Apis.uploadFile(imgData, image.name ?? "").then((response) {
      Obj.dismissLoading();
      var jsonMap = jsonDecode(response?.data ?? "");
      String? url = jsonMap["url"];
      if (url?.isNotEmpty ?? false) {
        debugPrint("上傳圖片到服務器成功 ${response?.data.toString()}");
        debugPrint("上傳圖片到服務器成功 ${image.path}");
        debugPrint("上傳圖片到服務器成功 ${url}");
        //成功 狀態待修改
        // message.copyWith(
        //   uri: url,
        // );
        final message = types.ImageMessage(
            author: _user!,
            createdAt: DateTime.now().millisecondsSinceEpoch,
            height: uiImage.height.toDouble(),
            id: const Uuid().v4(),
            name: image.name ?? "",
            size: imgData.length ?? 0,
            uri: url ?? "",
            width: uiImage.width.toDouble(),
            type: types.MessageType.image);
        _addMessage(message, imgUrl: url);
      }
    }).catchError((error) {
      Obj.dismissLoading();
      setState(() {});
    });
  }

  // 4. compress Uint8List and get another Uint8List.
  Future<Uint8List> testComporessList(Uint8List list) async {
    var result = await FlutterImageCompress.compressWithList(
      list,
      minWidth: 960,
      minHeight: 540,
      quality: 66,
      // rotate: 135,
    );
    debugPrint("testComporessList list.length=${list.length}");
    debugPrint("testComporessList result.length=${result.length}");
    return result;
  }

  void _handlePreviewDataFetched(
    types.TextMessage message,
    types.PreviewData previewData,
  ) {
    debugPrint("_handlePreviewDataFetched");
    final index = _messages.indexWhere((element) => element.id == message.id);
    final updatedMessage = (_messages[index] as types.TextMessage).copyWith(
      previewData: previewData,
    );
    setState(() {
      _messages[index] = updatedMessage;
    });
  }

  ///处理选中的图片
  void _handleImageSelection(ImageSource imageSource) async {
    debugPrint("_handleImageSelection");
    final result = await ImagePicker().pickImage(
      imageQuality: 70,
      maxWidth: 1440,
      source: imageSource,
    );

    if (result != null) {
      final bytes = await result.readAsBytes();
      final image = await decodeImageFromList(bytes);

      final message = types.ImageMessage(
          author: _user!,
          createdAt: DateTime.now().millisecondsSinceEpoch,
          height: image.height.toDouble(),
          id: const Uuid().v4(),
          name: result.name,
          size: bytes.length,
          uri: result.path,
          width: image.width.toDouble(),
          type: types.MessageType.image);

      ///1.先上傳圖片到服務器
      ///2.失敗的話狀態改失敗 再add進去
      Obj.showLoading();
      Apis.uploadFile(bytes, result.name).then((response) {
        Obj.dismissLoading();
        var jsonMap = jsonDecode(response?.data ?? "");
        String? url = jsonMap["url"];
        if (url?.isNotEmpty ?? false) {
          debugPrint("上傳圖片到服務器成功 ${response?.data.toString()}");
          debugPrint("上傳圖片到服務器成功 ${result.path}");
          //成功 狀態待修改
          message.copyWith(
            uri: url,
          );
          _addMessage(message, imgUrl: url);
        }
      }).catchError((error) {
        Obj.dismissLoading();
        setState(() {});
      });
    }
  }

  ///发送新消息处理
  void _handleSendPressed(types.PartialText message) {
    debugPrint("_handleSendPressed");
    final textMessage = types.TextMessage(
      author: _user!,
      createdAt: DateTime.now().millisecondsSinceEpoch,
      id: const Uuid().v4(),
      text: message.text,
    );

    _addMessage(textMessage);
  }

  ///消息点击处理
  void _handleMessageTap(BuildContext _, types.Message message) async {
    initPageIndex = 0;
    imgList.clear();
    if (message is types.FileMessage) {
      var localPath = message.uri;
      LogUtil.d("localPath $localPath");
      if (message.uri.startsWith('http')) {
        debugPrint("http");
        try {
          final index =
              _messages.indexWhere((element) => element.id == message.id);
          final updatedMessage =
              (_messages[index] as types.FileMessage).copyWith(
            isLoading: true,
          );

          setState(() {
            _messages[index] = updatedMessage;
          });

          final client = http.Client();
          final request = await client.get(Uri.parse(message.uri));
          final bytes = request.bodyBytes;
          final documentsDir = (await getApplicationDocumentsDirectory()).path;
          localPath = '$documentsDir/${message.name}';

          if (!File(localPath).existsSync()) {
            final file = File(localPath);
            await file.writeAsBytes(bytes);
          }
        } finally {
          final index =
              _messages.indexWhere((element) => element.id == message.id);
          final updatedMessage =
              (_messages[index] as types.FileMessage).copyWith(
            isLoading: null,
          );

          setState(() {
            _messages[index] = updatedMessage;
          });
        }
      }

      // await OpenFilex.open(localPath);
    } else if (message is types.ImageMessage) {
      setState(() {
        LogUtil.d("message is types.ImageMessage");
        LogUtil.d("_messages ${_messages.length}");
        _messages.forEach((element) {
          if (element is types.ImageMessage) {
            types.ImageMessage msg = element as types.ImageMessage;
            imgList.add(msg.uri);
          }
        });
        imgList.reversed;
        initPageIndex = imgList.indexWhere((element) => element == message.uri);
        if (imgList.isNotEmpty) {
          _pageController = PageController(initialPage: initPageIndex);
          showImageGallery = true;
          FocusManager.instance.primaryFocus?.unfocus();
        }
        LogUtil.d("imgList ${imgList}");
        LogUtil.d("imgList ${imgList.length}");
      });
    }
  }

  ///加載聊天記錄
  void _loadMessages(ChatRecord chatRecord) async {
    debugPrint("_loadMessages");
    if (chatRecord.rows.isNullOrEmpty) {
      return;
    }
    try {
      //降序
      chatRecord.rows?.sort((e1, e2) {
        return e2.sendtime!.compareTo(e1.sendtime.toString());
      });
      chatRecord.rows?.forEach((element) async {
        addNewMsgToList(
            msgtype: element.msgtype,
            senduserid: element.senduserid,
            id: element.id,
            sendtime: element.sendtime,
            sendtext: element.sendtext);
      });
    } catch (e) {
      debugPrint("加載歷史對話記錄失敗 $error");
    }
  }

  ///聘用
  void hire() {
    Obj.showLoading();
    var projectId = widget.message["projectId"];
    var adverseNo = widget.message["reviceuserId"];
    final params = {"projectId": projectId, "adverseNo": adverseNo};
    Apis.hireExpert(params).then((value) {
      Obj.dismissLoading();
      var result = ResponseBean.fromJson(value?.data ?? {});
      if (result.isRequestSuccess) {
        message['exhibition'] = false;
        isNeedUpdate = true;
        setState(() {});
        ToastUtil.showToast("聘用成功");
        eventBus.fire(UpdateOrderListEvent());
      }
    }).catchError((error) {
      Obj.dismissLoading();
    });
  }

  ///修改為已讀聊天狀態
  void updateChatReadState() {
    dynamic reviceuserId = message['reviceuserId'];
    dynamic projectNo = message['projectNo'];
    final params = {
      "projectNo": projectNo,
      "reciveuserid": reviceuserId,
      "senduserid": memberInfo?.data?.membersNo.toString() ?? ""
    };
    Apis.updateChatMsgRead(params).then((value) {
      var result = ResponseBean.fromJson(value?.data ?? {});
      if (result.isRequestSuccess) {
        LogUtil.d("updateChatMsgRead successful...");
        //刷新列表
        eventBus.fire(UpdateClientMsgListEvent());
      } else {
        LogUtil.d("updateChatMsgRead error:${result.msg}");
      }
    }).catchError((onError) {
      LogUtil.d("updateChatMsgRead error");
    });
  }

  ///獲取標籤等詳細信息
  void getDetailOfLabel() {
    if (AppConstant.userRole == UserRole.c) {
      return;
    }
    labelList!.clear();
    labelList = ["+ 加標籤"];
    var projectId = widget.message["projectId"];
    final pa = {"projectId": projectId};
    Apis.queryChatDetailOfProjectId(pa).then((value) {
      Obj.dismissLoading();
      chatDetailInfo = ChatDetailInfo.fromJson(value?.data ?? {});
      if (chatDetailInfo?.code == 200) {
        ///更新label
        var label = chatDetailInfo?.data?.projectLabel.toString();
        if (label.isNullOrEmpty) {
          return;
        }
        if (label == "null") {
          return;
        }
        var list = label?.split(',') ?? [];

        list.forEach((element) {
          if (element.isNotEmpty) {
            labelList!.add(element);
          }
        });

        LogUtil.d("list $list");
        LogUtil.d("labelList $labelList");
        setState(() {});
      } else {
        // ToastUtil.showToast(msg)
        Get.back();
      }
    }).catchError((error) {
      LogUtil.d("updateChatRecord error $error");
      Obj.dismissLoading();
    });
  }

  @override
  void dispose() {
    FocusManager.instance.primaryFocus?.unfocus();
    inputController.dispose();
    inputLabelController.dispose();
    refreshSubscription?.cancel();
    _chatScrollController.dispose();
    // cameraController?.dispose();
    super.dispose();
  }
}

class PreviewScreen extends StatelessWidget {
  final XFile imageFile;

  const PreviewScreen(this.imageFile);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        centerTitle: true,
        title: Text(
          '相機',
          style: getTextStyle(30.sp, color: Colors.blue),
        ),
        actions: [
          TextButton(
            // icon: const Icon(Icons.sen),
            onPressed: () {
              // 处理按钮点击事件
              Get.back(result: 100);
            },
            child: Align(
              alignment: AlignmentDirectional.center,
              child: Text(
                '發送',
                style: getTextStyle(20.sp, color: Colors.white),
              ),
            ),
          ),
        ],
      ),
      body: Center(
        child: Image.file(File(imageFile.path)),
      ),
    );
  }
}
